package com.funteam.globalalarm;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.TimeZone;

import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.DatePicker.OnDateChangedListener;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.TimePicker.OnTimeChangedListener;

public class AlarmMainActivity extends Activity implements OnDateChangedListener, OnTimeChangedListener, OnClickListener {
	
	protected static final int UPDATE_UI = 0;

	private AlarmManager mAlarmMng; // Alarm Manager
	private GregorianCalendar mCalendar; // Setting date
	private DatePicker mDatePicker;
	private TimePicker mTimePicker;
	private TextView mTvCurTimezone, mTvSetTimezoneName, mTvSetTimezoneDate;
	private RelativeLayout mRlSetTimezone;

	private String currentTime;

	private String[] mIdArray;
	private TimeZone mTimeArray;
	private NotificationManager mNotification;

	public static TimeZoneAdapter timezoneAdapter = null;
	public static TimeZoneAdapter timezoneAdapter1 = null;
	public static List<TimeZoneData> timezonelist = null;
	
	private int selected = 0;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.alarm_main);
		
		mIdArray = TimeZone.getAvailableIDs();
		mTimeArray = TimeZone.getTimeZone(mIdArray[0]);
		Log.d("@@@@@", "timeArray : " + mTimeArray);

		mNotification = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		mAlarmMng = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
		mCalendar = new GregorianCalendar();
		mTvCurTimezone = (TextView) findViewById(R.id.tv_current_timezone);
		mTvSetTimezoneName = (TextView) findViewById(R.id.tv_set_timezone_name);
//		tvSetTimezoneName.setText(timezoneAdapter.items.get(0).name);
		mTvSetTimezoneDate = (TextView) findViewById(R.id.tv_set_timezone_date);
//		tvSetTimezoneDate.setText(timezoneAdapter.items.get(0).time);
		mRlSetTimezone = (RelativeLayout) findViewById(R.id.rl_set_timezone);
		mRlSetTimezone.setOnClickListener(this);

		TimeZone CurTimezone = TimeZone.getDefault();
		// Date now = new Date();
		int CurTimeZoneOffset = CurTimezone.getRawOffset() / (60 * 60 * 1000);
		currentTime = String.valueOf(CurTimeZoneOffset);
		mTvCurTimezone.setText(getDisplayName(CurTimezone.getDisplayName()));
//		mTvCurTimezone.setText(CurTimezone.getDisplayName() + " : " + String.valueOf(CurTimeZoneOffset));

		timezonelist = new ArrayList<TimeZoneData>();
		// timezoneAdapter = new
		// TimeZoneAdapter(this,R.layout.view_timezone_spinner,timezonelist);

		// setListAdapter(timezoneAdapter);

		// idAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, idArray);
		 //idAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		 //mTimezoneIds.setAdapter(idAdapter);
		
//		timezoneAdapter = new TimeZoneAdapter(this, android.R.layout.simple_spinner_item, timezonelist);
//		timezoneAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		timezoneAdapter = new TimeZoneAdapter(this, android.R.layout.select_dialog_singlechoice, timezonelist);
		
//		spTimezoneIds.setAdapter(timezoneAdapter);
//		spTimezoneIds.setOnItemSelectedListener(new OnItemSelectedListener() {
//
//			@Override
//			public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//				String selectedId = (String) (parent.getItemAtPosition(position));
//				TimeZone timezone = TimeZone.getTimeZone(selectedId);
//				String TimeZoneName = timezone.getDisplayName();
//				int TimeZoneOffset = timezone.getRawOffset() / (60 * 60 * 1000);
//				tvSelTimezone.setText(TimeZoneName + " : " + String.valueOf(TimeZoneOffset));
//			}
//
//			@Override
//			public void onNothingSelected(AdapterView<?> arg0) {
//				// TODO Auto-generated method stub
//			}
//		});

		Log.i("AlarmMain", mCalendar.getTime().toString());

		Button btnSetAlarm = (Button) findViewById(R.id.btn_set_alarm);
		btnSetAlarm.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				setAlarm();
			}
		});

		Button btnResetAlarm = (Button) findViewById(R.id.btn_reset_alarm);
		btnResetAlarm.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				resetAlarm();
			}
		});

		mDatePicker = (DatePicker) findViewById(R.id.dp_datepicker);
		mDatePicker.init(mCalendar.get(Calendar.YEAR),
				mCalendar.get(Calendar.MONTH),
				mCalendar.get(Calendar.DAY_OF_MONTH), this);
		mTimePicker = (TimePicker) findViewById(R.id.tp_timepicker);
		mTimePicker.setCurrentHour(mCalendar.get(Calendar.HOUR_OF_DAY));
		mTimePicker.setCurrentMinute(mCalendar.get(Calendar.MINUTE));
		mTimePicker.setOnTimeChangedListener(this);
	}

	@Override
	protected void onStart() {
		super.onStart();

		String[] listItems = TimeZone.getAvailableIDs();

		TimeZone timezone = null;
		SimpleDateFormat format = new SimpleDateFormat(
				"EEE, MMM d, yyyy h:mm a");
		Date now = new Date();

		for (int index = 0; index < listItems.length; ++index) {
			timezone = TimeZone.getTimeZone(listItems[index]);

			format.setTimeZone(timezone);

			timezonelist.add(new TimeZoneData(getDisplayName(listItems[index]),
					format.format(now)));

			timezone = null;
		}
	}

	private String getDisplayName(String timezonename) {
		String displayname = timezonename;
		int sep = timezonename.indexOf('/');

		if (-1 != sep) {
			displayname = timezonename.substring(0, sep) + ", "
					+ timezonename.substring(sep + 1);
			displayname = displayname.replace("_", " ");
		}

		return displayname;
	}

	public class TimeZoneAdapter extends ArrayAdapter<TimeZoneData> {

		List<TimeZoneData> items = null;

		public TimeZoneAdapter(Context context, int textViewResourceId,
				List<TimeZoneData> items) {
			super(context, textViewResourceId, items);

			this.items = items;
		}

		@Override
		public int getCount() {
			return ((null != items) ? items.size() : 0);
		}

		@Override
		public TimeZoneData getItem(int position) {
			return ((null != items) ? items.get(position) : null);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View view = convertView;

			if (view == null) {
				LayoutInflater vi = (LayoutInflater) AlarmMainActivity.this
						.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				view = vi.inflate(R.layout.timezone_spinner, null);
			}

			TimeZoneData data = items.get(position);

			if (data != null) {
				TextView tvSpName = (TextView) view
						.findViewById(R.id.tv_sp_timezone_name);
				TextView tvSpTime = (TextView) view
						.findViewById(R.id.tv_sp_timezone_time);

				tvSpName.setText(data.name);
				tvSpTime.setText(data.time);
			}

			return view;
		}
	}

	// Set Alarm
	private void setAlarm() {
		mAlarmMng.set(AlarmManager.RTC_WAKEUP, mCalendar.getTimeInMillis(),
				pendingIntent());
		Log.i("AlarmMain", mCalendar.getTime().toString());
	}

	// Reset Alarm
	private void resetAlarm() {
		mAlarmMng.cancel(pendingIntent());
	}

	// Alarm setting intent
	private PendingIntent pendingIntent() {
		Intent i = new Intent(getApplicationContext(), AlarmMainActivity.class);
		PendingIntent pi = PendingIntent.getActivity(this, 0, i, 0);
		return pi;
	}

	// Time Changed Listener
	@Override
	public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
		mCalendar.set(mDatePicker.getYear(), mDatePicker.getMonth(),
				mDatePicker.getDayOfMonth(), hourOfDay, minute);
	}

	// Date Changed Listener
	@Override
	public void onDateChanged(DatePicker view, int year, int monthOfYear,
			int dayOfMonth) {
		mCalendar.set(year, monthOfYear, dayOfMonth,
				mTimePicker.getCurrentHour(), mTimePicker.getCurrentMinute());
	}

	@Override
	public void onClick(View v) {
		switch(v.getId()) {
		
		case R.id.rl_set_timezone:
			showTimezoneDialog();
			break;
		}
	}
	
	private void showTimezoneDialog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(AlarmMainActivity.this);
		builder.setTitle("Set TimeZone");

		builder.setAdapter(timezoneAdapter, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				selected = which;
				mTvSetTimezoneName.setText(timezoneAdapter.items.get(which).name);
				mTvSetTimezoneDate.setText(timezoneAdapter.items.get(which).time);
				dialog.dismiss();
//			}
			}
			
		});
//		builder.setSingleChoiceItems(idArray, selected,
//				new DialogInterface.OnClickListener() {
//
//					@Override
//					public void onClick(DialogInterface dialog, int which) {
//						selected = which;
//						tvSetTimezone.setText(idArray[which]);
//						dialog.dismiss();
//					}
//				});
		AlertDialog alert = builder.create();
		alert.show();
	}

}
